<template>
  <div>
    <div class="upload-box">
      <van-button class="record-button" @click="toggleRecord">
        <div class="record">
          <img src="imgs/uploadyp.png"/>
          <p v-if="!recording">点击开始录制</p>
          <p v-else style="display: flex;flex-direction: row">
            <van-loading color="#333333"></van-loading>录制中，点击以结束
          </p>
        </div>
      </van-button>
      <div class="tip">
        <div>
          <p>录制的音频长度不能超过1分钟</p>
        </div>
      </div>
      <div v-if="audioUrl" class="upload-box">
        <div class="audio-content">
          <audio controls :src="audioUrl"></audio>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { Dialog } from 'vant'
import Recorder from 'recorderjs'

@Component
export default class VoiceInput extends Vue {
  recording = false
  audioUrl = ''
  stream ?: MediaStream
  rec ?: any

  toggleRecord () {
    this.recording = !this.recording
    if (this.recording) {
      this.startRecord()
    } else {
      this.stopRecord()
    }
  }

  audioData (blob: Blob) {
    this.audioUrl = URL.createObjectURL(blob)
    const reader = new FileReader()
    reader.readAsDataURL(blob)
    reader.onload = e => {
      this.$store.state.api.voices = [(e.target?.result as string).split(',')[1]]
      this.$emit('dataOk', true)
    }
  }

  startRecord () {
    this.audioUrl = ''
    navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(stream => {
      console.log('getUserMedia() success, stream created, initializing Recorder.js ...')
      const audioContext = new AudioContext()
      this.stream = stream
      // eslint-disable-next-line no-undef
      this.rec = new Recorder(audioContext.createMediaStreamSource(this.stream), { numChannels: 1 })

      this.rec.record()

      console.log('Recording started')
    }).catch(err => {
      console.log(err)
      this.recording = false
      Dialog.alert({
        showConfirmButton: true,
        showCancelButton: false,
        title: '错误',
        message: '打开音频录制出错，请确认是否允许网页使用麦克风'
      })
    })
  }

  stopRecord () {
    console.log('Record stopped')
    if (this.rec !== null) {
      this.rec.stop()
    }
    if (this.stream !== undefined) {
      this.stream.getAudioTracks()[0].stop()
      this.stream = undefined
    }
    if (this.rec != null) {
      this.rec.exportWAV(this.audioData.bind(this))
    }
  }
}
</script>

<style scoped lang="less">
@import "common";

.upload-box {
  .record-button {
    width: 20.94rem;
    height: 12.5rem;
    background: #f7f8fa;
    border: 0;
    :hover {
      background: #f7f8fa;
    }
  }
  .record {
    p {
      font-family: PingFangSC-Regular;
      font-size: 1.25rem;
      color: #323333;
      font-weight: 600;
    }
  }
  .audio-content {
    width: 100%;
    audio {
      display: block;
      margin-top: 0.2rem;
      width: 100%;
    }
  }
}
</style>
